package client // Package client import "xemo.top/docker/docker/client"
import (
	"context"
	"encoding/json"
	"net/url"
	"xemo.top/docker/docker/api/types/container"
	"xemo.top/docker/docker/api/types/versions"
)

// ContainerWait 等待，直到指定的容器处于给定条件指示的特定状态，“未运行” (默认)，“下一个退出” 或 “已删除”。
// ContainerWait waits until the specified container is in a certain state indicated by the given condition,either "not-running" (default),"next-exit",or "removed".
//
// If this client's API version is before 1.30, condition is ignored and ContainerWait will return immediately with the two channels,as the server will wait as if the condition were "not-running".
//
// 如果此客户端的API版本至少为1.30，则ContainerWait将阻塞，直到服务器已确认请求 (带有响应标头)，然后返回两个通道，调用者可以在这两个通道上等待容器的退出状态，或者如果在开始等待请求或获取响应时出现问题，则返回错误。这允许调用者将ContainerWait与其他调用同步，例如在发出ContainerStart请求之前指定 “下一个退出” 条件
// If this client's API version is at least 1.30,ContainerWait blocks until the request has been acknowledged by the server (with a response header),then returns two channels on which the caller can wait for the exit status of the container or an error if there was a problem either beginning the wait request or in getting the response.This allows the caller to synchronize ContainerWait with other calls,such as specifying a "next-exit" condition before issuing a ContainerStart request
func (cli *Client) ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.ContainerWaitOKBody, <-chan error) {
	if versions.LessThan(cli.ClientVersion(), "1.30") {
		return cli.legacyContainerWait(ctx, containerID)
	}
	resultC := make(chan container.ContainerWaitOKBody)
	errC := make(chan error, 1)
	query := url.Values{}
	query.Set("condition", string(condition))
	resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", query, nil, nil)
	if err != nil {
		defer ensureReaderClosed(resp)
		errC <- err
		return resultC, errC
	}
	go func() {
		defer ensureReaderClosed(resp)
		var res container.ContainerWaitOKBody
		if err := json.NewDecoder(resp.body).Decode(&res); err != nil {
			errC <- err
			return
		}
		resultC <- res
	}()
	return resultC, errC
}

// legacyContainerWait 立即返回，并且没有等待容器被删除的选项。
// legacyContainerWait returns immediately and doesn't have an option to wait until the container is removed.
func (cli *Client) legacyContainerWait(ctx context.Context, containerID string) (<-chan container.ContainerWaitOKBody, <-chan error) {
	resultC := make(chan container.ContainerWaitOKBody)
	errC := make(chan error)
	go func() {
		resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", nil, nil, nil)
		if err != nil {
			errC <- err
			return
		}
		defer ensureReaderClosed(resp)
		var res container.ContainerWaitOKBody
		if err := json.NewDecoder(resp.body).Decode(&res); err != nil {
			errC <- err
			return
		}
		resultC <- res
	}()
	return resultC, errC
}
